package com.ljx.itbbs.server.mall.consumer;

import cn.hutool.json.JSONUtil;
import com.ljx.itbbs.server.mall.domain.entity.OrderEntity;
import com.ljx.itbbs.server.mall.domain.enums.PaymentStatusEnum;
import com.ljx.itbbs.server.mall.service.OrderService;
import com.ljx.itbbs.server.mq.domain.mall.CouponMsgDto;
import com.ljx.itbbs.server.mq.domain.mall.OrderMsgDto;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @Author: LiJunXi
 * @Description: 订单过期消费者
 * @Date: 2024-03-31  19:06
 */
@Slf4j
@Component
public class OrderExpireConsumer implements ChannelAwareMessageListener {

    @Lazy
    @Autowired
    private OrderService orderService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long tag = message.getMessageProperties().getDeliveryTag();
        String msg = new String(message.getBody());
        OrderMsgDto msgDto = JSONUtil.toBean(msg, OrderMsgDto.class);
        Long orderId = msgDto.getOrderId();
        OrderEntity order = orderService.getOrder(orderId);
        if (order.getPaymentStatus().equals(PaymentStatusEnum.DEFAULT.getType())) {
            // 未支付，订单失效
            orderService.updatePaymentStatus(orderId, PaymentStatusEnum.LOSE.getType());
        }
        // 确认消费
        channel.basicAck(tag, true);
    }
}
